/* eslint  react/no-string-refs: 0 */
import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import { Input, Grid, Form, Select, Message, Balloon, Icon, Radio,Dialog } from '@alifd/next';
import ModbusEditForm from './ModbusEditForm'
import SnmpEditForm from './SnmpEditForm'
import { observer, inject } from 'mobx-react';
import { ApiOfMetricCreate, ApiOfMetricUpdate } from '#/utils/coreApiDefine'
import './EditForm.scss';

const { Row, Col } = Grid;
const FormItem = Form.Item;

const formItemLayout = {
  labelCol: { xxs: 6, s: 3, l: 4 },
  wrapperCol: { s: 12, l: 12 }
};

const ruleFieldLabel = (<span>
  扩展配置：<Balloon type="primary" align="r" trigger={<Icon type="help" size="small" />} closable={false}>
    其它类型指标配置请查询用户手册
  </Balloon>
</span>);

const metricTypeDS = [
  {
    value: 'modbus',
    label: 'modbus'
  }, {
    value: 'snmp',
    label: 'snmp'
  }, {
    value: 'other',
    label: '其它'
  }
];

@inject('dictstore')
export default class SettingsForm extends Component {
  static displayName = 'EditForm';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    let formData = { ...this.props.formData };
    this.state = {
      value: {
        id: formData.id,
        name: formData.name,
        code: formData.code,
        variable: formData.variable,
        valueType: formData.valueType,
        unit: formData.unit,
        command: formData.command,
        rule: formData.rule,
        valueCategory: formData.valueCategory,
        comment: formData.comment
      },
      metricType: 'other',
      editSocketConfigDialogVisible: false,
      editSnmpConfigDialogVisible: false,
    };
  }

  formChange = (value) => {
    this.setState({
      value,
    });
  }

  onConfigInputFocus = () =>{
    console.log(this.state.metricType)
    const metricType = this.state.metricType;
    if(metricType=='modbus') {
      this.setState({
        editSocketConfigDialogVisible: true,
      })
    } else if(metricType=='snmp') {
      this.setState({
        editSnmpConfigDialogVisible: true,
      })
    }
  }

  onChange(metricType) {
    this.setState({
        metricType
    });
  }

  onCloseDialog = () => {
    this.setState({
      editSocketConfigDialogVisible: false,
      editSnmpConfigDialogVisible: false,
    });
  }

  onEditConfigConfirm = (values) => {
    let rule = JSON.stringify(values);
    let state = this.state
    state.value.rule = rule;
    state.editSocketConfigDialogVisible = false
    state.editSnmpConfigDialogVisible = false
    this.setState(state);
  }


  validateAllFormField = (values, errors) => {
    let that = this;
    if (!errors) {
      if (!!values.rule) {
        let isJSON = true;
        try {
          JSON.parse(values.rule)
        } catch (e) {
          isJSON = false
        }
        if (!isJSON) {
          Message.error('解析规则格式不正确！');
          return;
        }
      }
      let updated = values.id !== undefined;
      if (updated) {
        ApiOfMetricUpdate(values.code, values).then(() => that.props.submitCallback('success'))
      } else {
        ApiOfMetricCreate(values).then(() => that.props.submitCallback('success'))
      }
    } else {
      // 处理表单报错
    }
  }

  render() {
    return (
      <div className="settings-form">
        <IceContainer>
          <Form
            value={this.state.value}
            onChange={this.formChange}
            ref="form"
          >
            <div style={styles.formContent}>
              <Input name="id" htmlType="hidden" />
              <FormItem size="medium" label="名称：" {...formItemLayout} required maxLength={30} requiredMessage="必填">
                <Input name="name" placeholder="指标名称" />
              </FormItem>
              <FormItem size="medium" label="变量标识：" {...formItemLayout}>
                <Input name="variable" placeholder="指标变量标识" />
              </FormItem>
              <FormItem size="medium" label="数据类别：" {...formItemLayout} required requiredMessage="必填">
                <Select name="valueCategory" dataSource={this.props.dictstore.MetricValueCategoryDS} hasClear={true} style={{ width: '100%' }} />
              </FormItem>
              <FormItem size="medium" label="数据类型：" {...formItemLayout} required requiredMessage="必填">
                <Select name="valueType" dataSource={this.props.dictstore.MetricValueTypeDS} hasClear={true} style={{ width: '100%' }} />
              </FormItem>
              <FormItem size="medium" label="单位：" {...formItemLayout}>
                <Select name="unit" dataSource={this.props.dictstore.MetricUnitDS} hasClear={true} style={{ width: '100%' }} />
              </FormItem>
              <FormItem size="medium" label="指令：" {...formItemLayout}>
                <Input name="command" placeholder="指令" />
              </FormItem>
              <FormItem size="medium" label={ruleFieldLabel} {...formItemLayout}>
                <Radio.Group dataSource={metricTypeDS} value={this.state.metricType} onChange={this.onChange.bind(this)} />
                <Input.TextArea name="rule" onFocus={this.onConfigInputFocus.bind(this)}  placeholder="{... ...}" />
              </FormItem>
              <FormItem size="medium" label="注释" {...formItemLayout}>
                <Input.TextArea name="comment"  placeholder="注释" />
              </FormItem>
              <Row style={{ marginTop: 20 }}>
                <Col offset="3">
                  <Form.Submit
                    size="medium"
                    type="primary"
                    style={{ width: 100 }}
                    validate
                    onClick={this.validateAllFormField}
                  >
                    保 存
                  </Form.Submit>
                </Col>
              </Row>
            </div>
          </Form>

          <Dialog
            style={{ width: '50%' }}
            title="modbus解析配置"
            visible={this.state.editSocketConfigDialogVisible}
            footer={false}
            onClose={this.onCloseDialog}>
            <ModbusEditForm jsonConfig={this.state.value.rule} confirm={this.onEditConfigConfirm} />
          </Dialog>

          <Dialog
            style={{ width: '50%' }}
            title="snmp解析配置"
            visible={this.state.editSnmpConfigDialogVisible}
            footer={false}
            onClose={this.onCloseDialog}>
            <SnmpEditForm jsonConfig={this.state.value.rule} confirm={this.onEditConfigConfirm} />
          </Dialog>
        </IceContainer>
      </div>
    );
  }
}

const styles = {
  label: {
    textAlign: 'right',
  },
  formContent: {
    width: '100%',
    position: 'relative',
  },
  formItem: {
    alignItems: 'center',
    marginBottom: 25,
  },
  formTitle: {
    margin: '0 0 20px',
    paddingBottom: '10px',
    borderBottom: '1px solid #eee',
  },
};
